/*
 * @Description: 要货计划详情页面
 * @Version: 1.0
 * @Autor: c-jack.qian
 * @Date: 2021-02-23 15:16:13
 * @LastEditors: c-jack.qian
 * @LastEditTime: 2021-04-25 16:55:35
 */
import React, { useCallback, useEffect, useMemo, useRef } from 'react';
import { PageHeaderWrapper } from 'hzero-boot/lib/components/Page';
import { Button, DataSet, notification, Select, Table, TextField } from 'choerodon-ui/pro';
import { ButtonColor, FuncType } from 'choerodon-ui/pro/lib/button/enum';
import { useDataSet } from 'hzero-front/lib/utils/hooks';
import { DataSetProps } from 'choerodon-ui/pro/lib/data-set/DataSet';
import { TableAutoHeightType, TableColumnTooltip } from 'choerodon-ui/pro/lib/table/enum';
import intl from 'utils/intl';
import { routerRedux } from 'dva/router';
import querystring from 'querystring';
import { connect } from 'dva';
import {
  requireGoodsPlanDtlDS,
  productMakeDS,
  bigAreaMakeDS,
} from '../../stores/requireGoodsPlanDtlDS';
import { addEnterCallBack, renderSort, useQueryParams } from '../../utils/utilsFun';
import { Buttons } from 'choerodon-ui/pro/lib/table/Table';
import './indexDtl.less';
import CustomizeTableSearch from '@common/components/CustomizeTableSearch';
import commonConfigStore from '@common/config/commonConfig';
import ExcelExport from 'components/ExcelExport';
import formatterCollections from 'utils/intl/formatterCollections';
const O2_OM = process.env.NODE_ENV === 'development' ? '/o2om-c' : commonConfigStore.O2_OM;

notification.config({
  duration: 3,
  placement: 'bottomRight',
});

interface propType {
  props: any;
  match: any;
  dispatch: any;
  location: any;
}

const ClassPage: React.FC<propType> = props => {
  const tableDS = useDataSet(() => new DataSet(requireGoodsPlanDtlDS() as DataSetProps));
  const productMakingDS = useDataSet(() => new DataSet(productMakeDS() as DataSetProps));
  const bigAreaMakingDS = useDataSet(() => new DataSet(bigAreaMakeDS() as DataSetProps));

  const pageRef = useRef(null);
  // 添加按回车查询事件
  addEnterCallBack(tableDS, pageRef);

  const { search } = props.location;
  const queryStr: any = new URLSearchParams(search).get('params');
  const urlParamsObj = JSON.parse(decodeURIComponent(queryStr));
  const queryObj = useQueryParams(tableDS);

  useEffect(() => {
    reqData();
  }, []);

  const reqData = () => {
    const taskId = props.match.params.id;
    tableDS.setQueryParameter('taskId', taskId);
    tableDS.query();
  };

  const handleBatchExport = useCallback(() => {
    props.dispatch(
      routerRedux.push({
        pathname: `/o2om/distribution/excel-import/O2OM_C.REQUIREMENT_PLAN`,
        search: querystring.stringify({
          action: intl.get(`dji.otc.om.view.title.requireGoodsPlanImport`).d('要货计划列表导入'),
          prefixPath: 'O2OM_C.REQUIREMENT_PLAN',
          args: JSON.stringify({
            taskId: urlParamsObj.taskId,
            planMonth: urlParamsObj.planMonth,
          }),
        }),
      })
    );
  }, []);

  const columnsWrapHeader = (titel, content) => {
    return (
      <div style={{ lineHeight: '15px' }}>
        <span>{titel}</span>
        <br></br>
        <span>{content}</span>
      </div>
    );
  };

  const Columns = useMemo<any>(
    () => [
      {
        header: intl.get(`dji.otc.om.view.field.serialNumber`).d('序号'),
        width: 50,
        lock: true,
        renderer: ({ record }) => renderSort(record, tableDS),
      },
      {
        name: 'planMonth',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        lock: true,
      },
      { name: 'shortageType', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'version', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'planStatusCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'regionName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'areaName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'businessGroup', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'customerName', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'retailer', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'productCode', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'productName', align: 'left', tooltip: TableColumnTooltip.always },
      {
        name: 'quantityFirstWeek',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        header: () => columnsWrapHeader('T+1', 'WK1'),
      },
      {
        name: 'quantitySecondWeek',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        header: () => columnsWrapHeader('T+1', 'WK2'),
      },
      {
        name: 'quantityThirdWeek',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        header: () => columnsWrapHeader('T+1', 'WK3'),
      },
      {
        name: 'quantityFourthWeek',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        header: () => columnsWrapHeader('T+1', 'WK4'),
      },
      {
        name: 'quantityFifthWeek',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        header: () => columnsWrapHeader('T+2', 'WK1'),
      },
      {
        name: 'quantitySixthWeek',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        header: () => columnsWrapHeader('T+2', 'WK2'),
      },
      {
        name: 'quantitySeventhWeek',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        header: () => columnsWrapHeader('T+2', 'WK3'),
      },
      {
        name: 'quantityEighthWeek',
        align: 'left',
        tooltip: TableColumnTooltip.always,
        header: () => columnsWrapHeader('T+2', 'WK4'),
      },
      { name: 'quantityThirdMonth', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'quantityFourthMonth', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'quantityFifthMonth', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'quantitySixthMonth', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'importantProject', align: 'left', tooltip: TableColumnTooltip.always },
      { name: 'memo', align: 'left', tooltip: TableColumnTooltip.always },
    ],
    []
  );

  // 校验是否勾选数据
  const checkSelectData = () => {
    const seletedRecord = tableDS.selected;
    if (seletedRecord.length === 0) {
      notification.warning({
        placement: 'bottomRight',
        message: intl.get(`dji.otc.om.view.reminder.warning`).d('提示'),
        description: intl.get(`dji.otc.om.view.remind.checkTheData`).d('请勾选操作的数据'),
      });
      return false;
    } else {
      return true;
    }
  };

  const productComfirm = () => {
    if (checkSelectData()) {
      const selectRecord = tableDS.selected;
      productMakingDS.loadData(selectRecord);
      productMakingDS.submit().then(() => {
        tableDS.query();
      });
    }
  };

  const bigAreaComfirm = () => {
    if (checkSelectData()) {
      const selectRecord = tableDS.selected;
      bigAreaMakingDS.loadData(selectRecord);
      bigAreaMakingDS.submit().then(() => {
        tableDS.query();
      });
    }
  };

  const buttons: Buttons[] = [
    <div style={{ display: 'flex' }}>
      <Button
        icon="get_app"
        key="import"
        color={ButtonColor.default}
        funcType={FuncType.raised}
        onClick={() => handleBatchExport()}
      >
        {intl.get(`dji.otc.om.view.button.import`).d('导入')}
      </Button>
      <ExcelExport
        defaultSelectAll
        queryParams={queryObj}
        requestUrl={`${O2_OM}/v1/requirement-templates/export`}
        buttonText={intl.get(`dji.otc.om.view.button.exportMode`).d("导出模板")}
        defaultConfig={{
          fileName: intl
            .get('dji.otc.cle.view.title.requireGoodsPlanImportModel')
            .d('要货计划列表导入模版'), // 文件名
          fillerType: 'single-sheet', // 导出类型
        }}
        otherButtonProps={{
          style: { marginLeft: '10px' },
          funcType: 'flat',
        }}
      />
    </div>,
    // <Button icon="export" key="export" onClick={() => handleExportModel()}>
    //   {intl.get(`dji.otc.om.view.button.exportMode`).d('导出模板')}
    // </Button>,
  ];

  return (
    <div ref={pageRef}>
      <PageHeaderWrapper
        title={intl.get('dji.otc.om.view.menu.requireGoodsPlanDetail').d('要货计划详情')}
        header={
          <div style={{ display: 'flex', alignItems: 'center' }}>
            <Button onClick={() => productComfirm()} key="productMake">
              {intl.get(`dji.otc.om.view.button.marketingConfirmation`).d('产销确认')}
            </Button>
            <Button onClick={() => bigAreaComfirm()} key="regionComfirm">
              {intl.get(`dji.otc.om.view.title.bigAreaConfirmation`).d('大区确认')}
            </Button>
            {/* <Button onClick={() => handleDelete()} key="save">
            {intl.get(`dji.otc.om.view.button.save`).d('保存')}
          </Button> */}
            <Button onClick={() => productComfirm()} color={ButtonColor.primary} key="submit">
              {intl.get(`dji.otc.om.view.field.menu.create`).d('提交')}
            </Button>
          </div>
        }
        contentProps={{ className: 'columnsHeaderStyle' }}
      >
        <Table
          dataSet={tableDS}
          autoHeight={{ type: TableAutoHeightType.maxHeight, diff: 80 }}
          border
          columns={Columns}
          queryFieldsLimit={3}
          queryBar={props => (
            <CustomizeTableSearch
              elements={[
                <TextField name="customerName" key="customerName" />,
                <TextField name="productName" key="productName" />,
                <Select name="regionId" key="regionId" searchable />,
                <Select name="areaId" key="areaId" searchable />,
                <Select name="customerType" key="customerType" searchable />,
              ]}
              // eslint-disable-next-line react/jsx-props-no-spreading
              {...props}
            />
          )}
          buttons={buttons}
        />
      </PageHeaderWrapper>
    </div>
  );
};

export default connect()(
  formatterCollections({
    code: 'dji.otc.om',
  })(ClassPage)
);
